package com.liang.utils;

import com.liang.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;
;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
@Component
public class HtmlParesUtil {

//    public static void main(String[] args) throws Exception {
//            new HtmlParesUtil().parseJD("springboot").forEach(System.out::println);
//    }

    public List<Content> parseJD(String keywords) throws Exception {
        String url = "https://search.jd.com/Search?keyword="+keywords;


        Document parse = Jsoup.parse(new URL(url),30000);
        Element id = parse.getElementById("J_goodsList");

        Elements byTag = id.getElementsByTag("li");

        ArrayList<Content> goodsList = new ArrayList<>();

        for (Element el:byTag
        ) {
            String img = el.getElementsByTag("img").eq(0).attr("src");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();

            Content content = new Content();

            content.setTitle(title);
            content.setPrice(price);
            content.setImg(img);

            goodsList.add(content);
        }
        return goodsList;
    }
}
//    //获取请求 解析的url地址
//    //需要联网
//
//    String url = "https://search.jd.com/Search?keyword=java";
//
//    //解析网页（Jsoup返回Document 就是Document 对象）
//    Document parse = Jsoup.parse(new URL(url),30000);
//    Element id = parse.getElementById("J_goodsList");
//    //获取所有li标签
//    Elements byTag = id.getElementsByTag("li");
////      获取元素中内容，这里el就是每个li标签
//        for (Element el:byTag
//                ) {
//                String img = el.getElementsByTag("img").eq(0).attr("src");
//                String price = el.getElementsByClass("p-price").eq(0).text();
//                String title = el.getElementsByClass("p-name").eq(0).text();
